import Vue from 'vue'
import Router from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue';
import Cart from './views/Cart.vue';
import About from '@/views/About.vue'
import store from './store';
import History from './utils/history'

Vue.use(Router)
Vue.use(History) //作为插件方式挂载

// 在实例化之前，扩Router
//区分前进。后退
Router.prototype.goBack = function() {
  this.isBack = true; 
  //给将来的实例，动态添加一个属性isBack，说明当前行为是后退

  this.back(); //路由的后退方法
}

const router = new Router({
  mode: 'history',
  base: process.env.BASE_URL,
  routes: [
    {
      path: '/',
      name: 'home',
      component: Home
    },
    {
      path: '/login',
      name: 'login',
      component: Login
    },
    {
      path: '/cart',
      name: 'cart',
      component: Cart
    },
    {
      path: '/about',
      name: 'about',
      meta: { //这个路由上有meta.auth=true,就认为它是受保护的
        auth: true
      },
      component: About
    }
  ]
})

//全局路由守卫
router.beforeEach( (to, from, next) => {
  if(to.meta.auth){
    //auth为true，则需要认证，检查令牌

    if(store.state.token){ //已登录
      next()
    } else {
      //去登陆
      next({
        path: '/login',
        query: {redirect: to.path}
      })
    }
  } else {
    next();
  }
});

//afterEach记录历史记录
router.afterEach(( to, from) => {
  
  if (router.isBack) {
    //后退操作
    History.pop();
    console.log('History.isBack',History.isBack);
    
    router.isBack = false;
    //后退 页面的动画方式
    router.transitionName = 'route-back';
  } else {
    History.push(to.path); //要去的地址入栈

    console.log('History',History);
    
    //前进的 动画方式
    router.transitionName = 'route-forward';
  }

})

export default router;
